/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 *
 * @author Pawel
 */
public class VotingServer {
        private static final int port = 9999;
    private static final String host = "localhost";

    public static void main(String args[]) throws Exception {
        SocketAcceptor acceptor = new NioSocketAcceptor();
        acceptor.setReuseAddress(true);
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

        // SSL stuff

        File pKeyFile = new File("certs" + File.separatorChar + "mycakeystore.jks");
        String pKeyPassword = "bskbsk";
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");

        KeyStore keyStore = KeyStore.getInstance("JKS");
        
        keyStore.load(new FileInputStream(pKeyFile), pKeyPassword.toCharArray());
        
        keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
        InputStream keyInput = new FileInputStream(pKeyFile);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        KeyStore trustStore = KeyStore.getInstance("JKS");
        keyInput.close();
        
        keyInput = new FileInputStream(pKeyFile);
        trustStore.load(keyInput, pKeyPassword.toCharArray());
        trustManagerFactory.init(trustStore);
        keyInput.close();

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
        // end SSL stuff
        
        SslFilter sslFilter = new SslFilter(context);
        //sslFilter.setNeedClientAuth(false);//nie
        sslFilter.setWantClientAuth(true);
        sslFilter.setUseClientMode(false);
        chain.addLast("sslFilter", sslFilter);
      
        acceptor.setHandler(new VotingProtocolHandler());
        acceptor.getSessionConfig().setReadBufferSize(400000);
        acceptor.bind(new InetSocketAddress(port));
    }
}
